/*
 * @Date: 2022-03-29 12:47:50
 * @LastEditors: luoqi
 * @LastEditTime: 2022-04-12 09:27:30
 * @FilePath: /payment/pay/src/pages/AgencyTenant/AgencyTenantList.jsx
 */
import React, { useState, useEffect } from 'react';
import Tabs from '../../components/Tabs'
import axios from '../../util/axios'
import {
  Form,
  Input,
  InputNumber,
  Button,
  Table,
  Popover,
  Modal,
  Radio,
  Col,
  Row,
  Select,
  ConfigProvider,
  message

} from 'antd';
import {
  EditOutlined,
  ReloadOutlined,
  ScissorOutlined,
  RedEnvelopeOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import './AgencyTenantList.css'
import zhCN from 'antd/es/locale/zh_CN'
import CommonButton from '../../components/HOC/HocButton/CommonButton';

import qs from 'qs'
const { Option } = Select;

export default function AgencyTenantList() {
  //分页
  const [limit, setLimit] = useState(10);//每页条数
  const [pages, setpages] = useState(1);//当前页数
  const [count,setCount]=useState(1)//总共条数
  const [updataForm] = Form.useForm();//修改模态框表单内容
  // const [addForm] = Form.useForm();//修改模态框表单内容
  const [resetpwdForm] = Form.useForm();//修改密码模态框
  const [searchForm] = Form.useForm();//修改密码模态框
  const [addscoreForm] = Form.useForm();//充值表单
  const [deductscoreForm] = Form.useForm();//充值表单
  const [kaShangList, setkaShangList] = useState([])//卡商列表
  //
  // 定义表格一行内容
  const [rowInfo, setRowinfo] = useState({});
  //模态框显示状态
  // 1、修改的modal
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 2、重置密码的modal
  const [isModalVisiblePwd, setIsModalVisiblePwd] = useState(false);
  // 3、充值
  const [isModalVisiblePay, setIsModalVisiblePay] = useState(false);
  // 4、扣除
  const [isModalVisibleDeduct, setIsModalVisibleDeduct] = useState(false);

  //模态框功能状态 true-修改功能 false-开户功能
  const [isModify, setIsModify] = useState(false);
  // 模态修改列表表单数据
  let modifyFormData = {
    name: "张三",
    nickName: "qwwee",
    kashang: "1212",
    ApiList: "122",
    LoginIP: "12",
    dong_jie_jin_e: "12",
    rechargeRate: "21",
    accountState: "12",
    daiFuState: 0,
    isOpenLogin: "",
    md5_secre: "",
    AES: ""
  }
  //修改模态框确认按钮 获中表单数据
  const handleOkUpdata = () => {
    let updataFormInfo = updataForm.getFieldValue()
    console.log('修改模态框', updataFormInfo);
    // if(!updataFormInfo.kashang){
    //   updataFormInfo.kashang=updataFormInfo.kashang.toString()
    //   console.log('修改模态框后', updataFormInfo);
    // }
    
    
    axios({
      method: 'post',
      url: 'admin/shanghuliebiao/updateShangHu',
      headers: {
        'content-type': 'application/json'
      },
      data: updataFormInfo
    }).then(res => {
      console.log(res);
      if (res.code === 200) {
        gettableData();
        message.success('用户信息修改成功');
      }
    })
    setIsModalVisible(false); //隐藏模态框
  }
  //获取卡商列表
  const getKsData = () => {
    axios({
      method: 'get',
      url: 'admin/rujinqinqiu/selectAllRuJinQinQiu',
      params: { limit: 9999, page: 1 }
    }).then(res => {
      let dataArr = res.data.ruJinQinQiuList.map((item, index) => {
        item.key = index
        return item
      });
      console.log(dataArr);
      console.log(res.count);
      setkaShangList(res.data.kaShangList)
    })

  }
  //点击修改获取一行数据
  const Agencyupdata = () => {
    setIsModalVisible(true); //显示模态框
    setIsModify(true)//模态框状态
    console.log('点击修改获取一行数据', rowInfo);
    updataForm.setFieldsValue(rowInfo)//
  }
  //搜索
  const serchFn = () => {
    console.log(searchForm.getFieldValue());
    let name1 = searchForm.getFieldValue().name;
    axios({
      method: 'get',
      url: 'admin/shanghuliebiao/selectShangHu',
      // params:qs.stringify({limit:5,name:name1,page:1})
      params: { limit: 5, name: name1, page: 1 }
    }).then(res => {
      console.log(res);
      setdata(res.data)
    })
  }
  //重置md5_secre密钥
  const reMD = () => {
    Modal.confirm({
      title: '信息',
      icon: <ExclamationCircleOutlined />,
      content: '是否重置md5_secre Secret',
      okText: '确认',
      cancelText: '取消',
    });
  }
  //重置登录密码
  const reLoginPwd = () => {
    console.log(11);
    setIsModalVisiblePwd(true)
  }
  // 充值
  const pay = () => {
    setIsModalVisiblePay(true);
  }
  //扣除
  const deduct = () => {
    setIsModalVisibleDeduct(true)
  }
  //模态框确定
  const handleOk = () => {
    setIsModalVisible(false);
  };
  //重置密码确定
  const rePwdOk = () => {
    setIsModalVisiblePwd(false);
    let password = resetpwdForm.getFieldValue().Loginpassword;
    let yongHuId = rowInfo.yongHuId;
    console.log(yongHuId);
    axios({
      method: 'POST',
      url: 'admin/shanghuliebiao/resetPassword',
      data: qs.stringify({ password, yongHuId: Number(yongHuId) })
    }).then(res => {
      // console.log(res);
      if(res.code===200){
        message.success('密码修改成功');
      }
    })
    resetpwdForm.resetFields();

  };
  //确认充值
  const payOk = () => {
    setIsModalVisiblePay(false);
    let addInfo=addscoreForm.getFieldValue();
    let money=addInfo.money*1;
    // console.log(addInfo);
    console.log(money);
    axios({
      method:'post',
      url:'admin/shanghuliebiao/addScore',
      data:qs.stringify({
        money:money,
        yongHuId:rowInfo.yongHuId
      })
    }).then(res=>{
      if(res.code===200){
        message.success('充值成功');
        addscoreForm.resetFields()
      }
    })
  };
  //确认扣除
  const deductOk = () => {
    setIsModalVisibleDeduct(false);
    let deductinfo=deductscoreForm.getFieldValue();
    let money=deductinfo.money*1;
    axios({
      method:'post',
      url:'admin/shanghuliebiao/reduceScore',
      data:qs.stringify({
        money:money,
        yongHuId:rowInfo.yongHuId
      })
    }).then(res=>{
      if(res.code===200){
        message.success('扣除成功');
        deductscoreForm.resetFields()
      }
    })

  };
  // 模态框取消
  const handleCancel = () => {
    console.log('关闭');
    updataForm.resetFields()

    setIsModalVisible(false);
  };
  const rePwdCancel = () => {
    setIsModalVisiblePwd(false);
  };
  const payCancel = () => {
    setIsModalVisiblePay(false);
  };
  const deductCancel = () => {
    setIsModalVisibleDeduct(false);
  };
  //气泡弹框操作内容
  const content = (
    <div>
      <ul className='doList'>
        <li onClick={Agencyupdata}><EditOutlined />  修改</li>
        {/* <li onClick={reMD}><ReloadOutlined />  重置MD5密钥</li> */}
        <li onClick={reLoginPwd}><ReloadOutlined />  重置登录密码</li>
        <li onClick={pay}><RedEnvelopeOutlined />  充值</li>
        <li onClick={deduct}><ScissorOutlined />  扣除</li>
      </ul>

    </div>
  );
  // 开户
  const openAccount = () => {
    // 修改模态框功能
    setIsModify(false);
    //显示模态框
    setIsModalVisible(true);
    console.log('开户');
    updataForm.resetFields();//清空
   
  }
  //确认开户
  const handleOkAdd=()=>{
    let addInfo=updataForm.getFieldValue();
    // if(!addInfo.kashang){
    //   addInfo.kashang=addInfo.kashang.toString()
    // }
    console.log(addInfo);
    axios({
      method:'post',
      url:'admin/shanghuliebiao/addShangHu',
      headers: {
        'content-type': 'application/json'
      },
      data: addInfo, 
      // data:addInfo
    }).then(res=>{
      if(res.code===200){
        setIsModalVisible(false);
        message.success('添加商户成功');
        updataForm.resetFields();//清空
        gettableData();

      }
    })
  }
  //刷新
  const reload=()=>{
    gettableData();
  }
  //分页
  const pagesFn = (current, pageSize) => {
    console.log(current, pageSize);
    setLimit(pageSize);
    setpages(current);

  }
  const changePage=(current)=>{
    console.log('当前页',current);
    setpages(current);
    gettableData()
  }
  // 表格名
  const columns = [
    {
      title: '用户名',
      dataIndex: 'name',
      fixed: 'left',
      align: 'center'
    },
    {
      title: '用户号',
      dataIndex: 'yongHuId',
      fixed: 'left',
      align: 'center'
    },
    {
      title: '商户名称',
      dataIndex: 'nickName',
      fixed: 'left',
      align: 'center'
    },
    // {
    //   title: '是否代理',
    //   dataIndex: 'is_agent',
    //   align: 'center',
    //   render: (text, record, index) => {
    //     return record.is_agent === '商户' ? <span style={{ color: 'greenyellow' }}>商户</span> : record.is_agent === '代理' ? <span style={{ color: 'blue' }}>代理</span> : ''
    //   }
    // },
    // {
    //   title: '总余额',
    //   dataIndex: 'zong_yu_e',
    //   align: 'center'
    // },
    {
      title: '冻结金额',
      dataIndex: 'dongJieJinE',
      align: 'center'
    },
    {
      title: '账号状态',
      dataIndex: 'accountState',
      align: 'center',
      sorter: (a, b) => a.accountState - b.accountState,
      multiple: 1,
      render: (text, record, index) => {
        return record.accountState === 1 ? <span style={{ color: 'greenyellow' }}>正常</span> : <span style={{ color: 'blue' }}>冻结</span>
      }
    },
    {
      title: '代付状态',
      dataIndex: 'daiFuState',
      align: 'center',
      sorter: (a, b) => a.daiFuState - b.daiFuState,
      multiple: 2,
      render: (text, record, index) => {
        return record.daiFuState === 1 ? <span style={{ color: 'greenyellow' }}>正常</span> : <span style={{ color: 'blue' }}>冻结</span>
      }
    },
    {
      title: '充值费率(%)',
      dataIndex: 'rechargeRate',
      align: 'center'
    },
    {
      title: '开户时间',
      dataIndex: 'createTime',
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'do',
      align: 'center',
      render: (text, record, index) => (
        <Popover content={content}
          trigger="click"
          onClick={() => setRowinfo(record)}
          placement="bottomLeft" >
          <Button type="primary">操作</Button>
        </Popover>

      ),
      fixed: 'right',
    },
  ];
  // let data = [
  //   {
  //     key: '1',
  //     name: 'John Brown',//商户名
  //     yongHuId: '1220220127563688282',//商户ID
  //     nickName: '123456',
  //     is_agent: '商户',
  //     zong_yu_e: '81.16',
  //     dong_jie_jin_e: '200.00',
  //     accountState: '正常',
  //     daiFuState: '正常',
  //     rechargeRate: '10',
  //     md5_secre: 'QuOqiAsUhry2xWvheZAoflwj3wKHRpzD',
  //     google_secret: 'QuOqiAsUhry2xWvheZAoflwj3wKHRpzD',
  //     createTime: '2022-01-27 14:22:11',
  //     do: '操作'
  //   },
  // ];
  //表格数据
  let [data, setdata] = useState()
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record) => ({
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  //渲染表格函数
  const gettableData = () => {
    axios({
      method: 'get',
      url: 'admin/shanghuliebiao/selectAllShangHu',
      params: { limit: 9999, page: pages }
    }).then(res => {
      // console.log(res.data);
      let dataArr = res.data.map((item, index) => {
        item.key = index
        return item
      });
      // console.log(dataArr);
      console.log(res.count);
      setCount(res.count);
      setdata(dataArr)
      
    })

  }
  useEffect(() => {
    gettableData();
    getKsData()
  }, [])
  return (
    <div>
      <ConfigProvider locale={zhCN}>
        <Tabs title={'代理商户列表'}>代理商户列表</Tabs>
        {/* 表单搜索栏 */}
        <div style={{ 'margin': '20px 0' }}>
          <Form
            form={searchForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 24 }}
            layout="inline"
            onFinish={serchFn}
          >

            <Form.Item name="name">
              <Input placeholder="用户名/商品号" />
            </Form.Item>
            <Form.Item >
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
            </Form.Item>
            <Form.Item >
              <CommonButton type="primary" buttonName="开户" icon={<PlusOutlined />} className="yellow" handlerClick={openAccount} ></CommonButton>
              {/* <Button type="primary" onClick={openAccount} icon={<PlusOutlined />}>开户</Button> */}
            </Form.Item>
           
            <Form.Item >
            <Button  shape="circle" icon={<ReloadOutlined />} onClick={reload} />
            </Form.Item>
          </Form>

        </div>
        {/* 表格内容 */}
        <div>
          <Table
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            columns={columns}
            dataSource={data}
            scroll={{ x: 1800 }}
            pagination={{ 
              showSizeChanger: true, 
              showQuickJumper: true,
              // total:count,
              // onChange: (current) => changePage(current),
              onShowSizeChange: (current, pageSize) => (pagesFn(current, pageSize)) }}
          />
        </div>
        {/* 模态框 */}
        <Modal title={isModify ? "基本信息" : "添加商户"} visible={isModalVisible} onOk={isModify ? handleOkUpdata : handleOkAdd} onCancel={handleCancel} okText="确认"
          cancelText="取消" width={1000}>
          <Form
            name="modal"
            form={updataForm}
            onFinish={handleOkUpdata}
            autoComplete="off"
            layout="inline"
            initialValues={{
              // accountState: '1',
              // daiFuState: '1',
              isOpenLogin: '1',
              roleId:2
            }}
          >
            <Row >
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="用户名"
                  name="name"
                 
                >
                  {/* <Input defaultValue={isModify ? modifyFormData.name : ''} /> */}
                  {isModify ? <Input readOnly /> : <Input />}

                </Form.Item>
              </Col>
            
              <Col span={24} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="商户名"
                  name="nickName"
                  rules={[{ required: true, message: '请输入商户名' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={24} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="卡商"
                  name="kashang"
                  rules={[{ required: true, message: '请选择卡商' }]}
                >
                  <Select
                    allowClear
                    style={{ width: '100%' }}
                    placeholder="请选择卡商"
                  // defaultValue={isModify ? modifyFormData.kashang : ''}
                  // onChange={handleChange}
                  >
                    {/* <Option value='微笑' >微笑</Option>
                    <Option value='test'>test</Option>
                    <Option value='1'>1</Option> */}
                    {kaShangList.map((item, index) => {
                  return (<Select.Option key={index} value={item.nickName} >{item.nickName}</Select.Option>)
                })
                }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="上级代理"
                  name="shangJi"
                  rules={[{ required: true}]}
                >
                  <Input />

                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="代理权限"
                  name="roleId"
                >
                  <Radio.Group >
                    <Radio value={2}>启用</Radio>
                    <Radio value={3}>关闭</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="冻结金额(元)"
                  name="dongJieJinE"
                >
                  {/* <Input defaultValue={isModify ? modifyFormData.dong_jie_jin_e : ''} /> */}
                  <InputNumber />
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="充值费率(%)"
                  name="rechargeRate"
                  rules={[{ required: true}]}
                >
                  <InputNumber />
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item name="accountState" label="账号状态" rules={[{ required: true}]}>
                  <Radio.Group >
                    <Radio value={1}>正常</Radio>
                    <Radio value={0}>冻结</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item name="daiFuState" label="代付状态" rules={[{ required: true}]}>
                  <Radio.Group >
                    <Radio value={1}>正常</Radio>
                    <Radio value={0}>冻结</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
               <Col span={12} style={{ margin: '12px 0' }}>
               {isModify ? "" : 
               <Form.Item
                  label="密码"
                  name="password"
                  rules={[{ required: true}]}
                >
                   <Input />
                </Form.Item>
                }
              </Col> 
              {/* <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item name="isOpenLogin" label="是否启用登录白名">
                  <Radio.Group >
                    <Radio value={1} >关闭</Radio>
                    <Radio value={2}>启用</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col> 
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="md5_secre Secret"
                  name="md5_secre"
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12} style={{ margin: '12px 0' }}>
                <Form.Item
                  label="AES Secret"
                  name="AES"
                >
                  <Input />
                </Form.Item>
              </Col>*/}
            </Row>
          </Form>

        </Modal>

        <Modal title='重置登录密码' visible={isModalVisiblePwd} onOk={rePwdOk} onCancel={rePwdCancel} okText="确认"
          cancelText="取消" >

          <Form
            form={resetpwdForm}
            name="modal"
            onFinish={handleOk}
            autoComplete="off"

          >
            <Form.Item
              label="登录密码"
              name="Loginpassword"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="重复登录密码"
              name="rePassword"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
          </Form>

        </Modal>

        <Modal title='充值' visible={isModalVisiblePay} onOk={payOk} onCancel={payCancel} okText="确认"
          cancelText="取消" >

          <Form
           form={addscoreForm}
            name="modal"
            onFinish={handleOk}
            autoComplete="off"
            initialValues={{
              newMoney:'是'
            }}

          >
            <Form.Item
              label="新资金"
              name="newMoney"

            >
              <Radio.Group name="payRadio" >
                <Radio value='是'>是</Radio>
                <Radio value='否'>否</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              label="充值金额"
              name="money"
              rules={[
                {
                  required: true,
                  message: '请输入充值金额',
                },
              ]}
            >
              <Input />
            </Form.Item>
      
          </Form>

        </Modal>
        <Modal title='扣除' visible={isModalVisibleDeduct} onOk={deductOk} onCancel={deductCancel} okText="确认"
          cancelText="取消" >

          <Form
            form={deductscoreForm}
            name="modal"
            onFinish={handleOk}
            autoComplete="off"

          >

            <Form.Item
              label="扣除金额"
              name="money"
              rules={[
                {
                  required: true,
                  message: '请输入扣除金额',
                },
              ]}
            >
              <Input />
            </Form.Item>
           

          </Form>

        </Modal>
      </ConfigProvider>
      
    </div>
  )
}
